//
//  B_ChangePasswordVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/8/19.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_ChangePasswordVC.h"
#import "B_ReleaseFooterView.h"
#import "B_ChangePasswordTVC.h"
#import "B_AddBankModel.h"
#import "NSString+DES.h"

@interface B_ChangePasswordVC ()<UITextFieldDelegate>
@property (nonatomic, strong) BaseTableView * mainView;

@property (nonatomic, strong) B_ReleaseFooterView * logoutView;
@end

@implementation B_ChangePasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"修改密码"];
    self.view = self.mainView;
    B_AddBankModel * model0 = [B_AddBankModel initB_AddBankModelWithTitle:@"" placeholder:@"请输入手机号" mapword:@"手机号" alert:@"请输入手机号"];
    model0.value_name = getMobile();
    B_AddBankModel * model1 = [B_AddBankModel initB_AddBankModelWithTitle:@"" placeholder:@"请输入验证码" mapword:@"验证码" alert:@"请输入验证码"];
    B_AddBankModel * model2 = [B_AddBankModel initB_AddBankModelWithTitle:@"" placeholder:@"请输入密码" mapword:@"密码0" alert:@"请输入密码"];
//    B_AddBankModel * model3 = [B_AddBankModel initB_AddBankModelWithTitle:@"" placeholder:@"确认新密码" mapword:@"密码1" alert:@"请确认新密码"];
    
    self.dataArray = [NSMutableArray arrayWithObjects:model0, model1, model2 /*, model3*/, nil];
}

- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        [_mainView addSubview:self.logoutView];
        [self.logoutView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mainView.mas_left);
            make.right.equalTo(self.mainView.mas_right);
            make.bottom.equalTo(self.mainView.mas_bottom);
            make.height.equalTo(@(80));
        }];
        CGFloat bottom = SCREEN_HEIGHT > 800 ? (80 + 24) : 80;
        [_mainView setTableViewFrameWithTop:5 left:0 right:0 bottom:-bottom];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_ChangePasswordTVC" bundle:nil] forCellReuseIdentifier:@"B_ChangePasswordTVC"];
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return weSelf.dataArray.count;
        };
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 70;
        };
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            B_AddBankModel * model = weSelf.dataArray[indexPath.row];
            B_ChangePasswordTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_ChangePasswordTVC" forIndexPath:indexPath];
            cell.B_textfield.text = model.value_name;
            cell.B_textfield.placeholder = model.placeholder_name;
            cell.B_textfield.delegate = weSelf;
            cell.B_textfield.tag = indexPath.row;
            if ([model.map_word isEqualToString:@"验证码"]) {
                cell.B_getcodeButton.hidden = NO;
                cell.B_textfield.keyboardType = UIKeyboardTypeNumberPad;
                cell.getCode = ^{
                    //TODO:获取验证码
                    [weSelf getCodeData];
                };
            } else {
                cell.B_getcodeButton.hidden = YES;
                cell.B_textfield.keyboardType = UIKeyboardTypeDefault;
            }
            return cell;
        };
        _mainView.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            
        };
        
    }
    return _mainView;
}

- (B_ReleaseFooterView *)logoutView {
    WeakSelf(weSelf, self);
    if (!_logoutView) {
        _logoutView = [B_ReleaseFooterView initB_ReleaseFooterView];
        [_logoutView.B_SureButton setTitle:@"确认提交" forState:UIControlStateNormal];
        _logoutView.sureActionBlock = ^{
            //TODO:执行修改密码
            [weSelf submitData];
        };
    }
    return _logoutView;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    B_AddBankModel * model = self.dataArray[textField.tag];
    model.value_name = textField.text;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/**
 TODO:修改密码提交
 */
- (void) submitData {
    [self.view endEditing:YES];
    for (B_AddBankModel * model in self.dataArray) {
        if (ISNULL(model.value_name)) {
            [KeyWindow makeToast:model.map_word];
            return;
        }
    }
    B_AddBankModel * model0 = self.dataArray[0];
    B_AddBankModel * model1 = self.dataArray[1];
    B_AddBankModel * model2 = self.dataArray[2];
    
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/login/editPassword" parameters:@{@"str": [NSString getEncypt:@{@"XxwyzValidateCode":model1.value_name, @"XxwyzMobile":model0.value_name,                                                                                                                         @"XxwyzPassword" : [model2.value_name MD5], @"XxwyzCode":@"158178"}]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] intValue] == 10025) {
            [KeyWindow makeToast:@"修改成功!"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
    
    
    
    
}

/**
 TODO:获取验证码
 */
- (void) getCodeData {
    [self.view endEditing:YES];
    B_AddBankModel * model = self.dataArray[0];
    if (ISNULL( model.value_name)) {
        [KeyWindow makeToast:@"请输入手机号"];
        return;
    } else {
        if ( [model.value_name isMobileNumber] ) {
            
        } else {
            [KeyWindow makeToast:@"请输入有效手机号"];
            return;
        }
    }
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/login/mobelSendMessage" parameters:@{@"str": [NSString getEncypt:@{@"LiZhenyangMobilePhone": model.value_name, @"LiZhenyangCode":@"178180"}]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] intValue] == 10015) {
            [KeyWindow makeToast:@"验证码获取成功,请注意查收!"];
            [self timeFire];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

/**
 倒计时
 */
- (void) timeFire {
    //验证码获取时间倒计时
    __block int timeout = 59; //倒计时时间
    //优先级
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    B_ChangePasswordTVC * cell = [self.mainView.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 （倒计时结束后调用）
                [cell.B_getcodeButton setTitle:@"验证码" forState:UIControlStateNormal];
                //设置不可点击
                cell.B_getcodeButton.userInteractionEnabled = YES;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
                
            });
        }else{
            //
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [cell.B_getcodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                //设置不可点击
                cell.B_getcodeButton.userInteractionEnabled = NO;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
